#!/bin/bash

# ANSI 颜色代码
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'  # 重置颜色

# 模型生成的CPP代码目录
DIR="generated_ascend_codes/codes"
SUCCESS_LOG="$PWD/success.log"
FAIL_LOG="$PWD/fail.log"

# 清空旧日志（如果存在）
> "$SUCCESS_LOG"
> "$FAIL_LOG"

# 检查目录是否存在
if [ ! -d "$DIR" ]; then
    echo "Error: Directory $DIR does not exist."
    exit 1
fi

# 计数器
TOTAL=0
SUCCESS=0
FAIL=0

echo "===== Start Processing ====="

# 遍历所有cpp文件并检验每个cpp文件是否可以通过编译
find "$DIR" -type f -name "*.cpp" | while read -r cpp_file; do
    if [ -f "$cpp_file" ]; then
        ((TOTAL++))
        abs_path=$(realpath "$cpp_file")
        echo "Processing [$TOTAL/$((TOTAL + FAIL))]: $abs_path..."

        # 尝试执行 run.sh，并捕获错误
        cd ..
        if bash run.sh "$abs_path" 2>&1; then
            echo "[OK] Processed: $cpp_file" >> "$SUCCESS_LOG"
            ((SUCCESS++))
        else
            echo "[ERROR] Failed to process: $cpp_file" >> "$FAIL_LOG"
            ((FAIL++))
        fi
        cd -
    fi
done

# 打印统计结果
echo "===== Result ====="
echo "Total files: $TOTAL"
echo "Success: $SUCCESS"
echo "Failed: $FAIL"
echo "------------------"

# 打印成功日志（绿色）
echo -e "${GREEN}===== SUCCESSFUL PROCESSED FILES =====${NC}"
if [ -s "$SUCCESS_LOG" ]; then
    while IFS= read -r line; do
        echo -e "${GREEN}$line${NC}"
    done < "$SUCCESS_LOG"
else
    echo "No successful files."
fi

# 打印失败日志（红色）
echo -e "\n${RED}===== FAILED PROCESSED FILES =====${NC}"
if [ -s "$FAIL_LOG" ]; then
    while IFS= read -r line; do
        echo -e "${RED}$line${NC}"
    done < "$FAIL_LOG"
else
    echo "No failed files."
fi


# 如果有失败，返回非0状态码
if [ "$FAIL" -gt 0 ]; then
    exit 1
fi